package priv.wangy.micro.common.constant;


import priv.wangy.micro.common.po.http.rspn.BaseListRspn;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 简单的数据字典
 *
 * @author zhangjq
 * @see SimpleField
 * @since 2024-04-24
 */
public class SimpleDictionary extends BaseDictionary{

    private static final Map<Class<? extends SimpleDictionary>, List<? extends SimpleField>> FIELD_LIST = new HashMap<>();

    private static List<? extends SimpleField> getFieldList(Class<? extends SimpleDictionary> clazz) {
        if (FIELD_LIST.containsKey(clazz)) {
            return FIELD_LIST.get(clazz);
        }
        List<SimpleField> result = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (Modifier.isStatic(field.getModifiers()) && SimpleField.class.isAssignableFrom(field.getType())) {
                field.setAccessible(true);
                try {
                    result.add((SimpleField) field.get(null));
                } catch (IllegalAccessException ignore) {
                }
            }
        }
        FIELD_LIST.put(clazz, result);
        return result;
    }

    public static SimpleField getDictByValue(String value, Class<? extends SimpleDictionary> clazz) {
        return getFieldList(clazz).stream()
                .filter(f -> Objects.equals(f.getValue(), value)).findFirst()
                .orElse(null);
    }

    public static SimpleField getDictByDisplay(String display, Class<? extends SimpleDictionary> clazz) {
        return getFieldList(clazz).stream()
                .filter(f -> Objects.equals(f.getDisplay(), display)).findFirst()
                .orElse(null);
    }

    public static String getDisplayByValue(String value, Class<? extends SimpleDictionary> clazz) {
        return getFieldList(clazz).stream()
                .filter(f -> Objects.equals(f.getValue(), value)).findFirst().map(SimpleField::getDisplay)
                .orElse(null);
    }

    public static String getValueByDisplay(String display, Class<? extends SimpleDictionary> clazz) {
        return getFieldList(clazz).stream()
                .filter(f -> Objects.equals(f.getDisplay(), display)).findFirst().map(SimpleField::getValue)
                .orElse(null);
    }

    public static BaseListRspn.Field getListRspnField(Class<? extends SimpleDictionary> clazz) {
        return new BaseListRspn.Field(getListRspnFieldName(clazz),
                getFieldList(clazz).stream()
                        .map(f -> new BaseListRspn.Field.Property(f.getValue(), f.getDisplay()))
                        .collect(Collectors.toList()));
    }
}
